package com.stud.seckill.common.auth;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.stud.seckill.common.config.Constant;
import com.stud.seckill.common.config.RedisService;
import com.stud.seckill.entity.UserEntity;
import com.stud.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问限制拦截器
 */
@Component
public class AccessInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            // 获取登录用户信息
            UserEntity user = getUser();
            // 放到线程里
            UserContext.setUser(user);
        }
        return true;
    }

    /**
     * 获取登录信息
     * @return
     */
    private UserEntity getUser() {
        if (StpUtil.isLogin()) {
            Long userId = StpUtil.getLoginIdAsLong();
            return userService.getById(userId);
        }
        return null;
    }

    /**
     * 获取登录信息
     * @param request
     * @param response
     * @return
     */
    private UserEntity getUser(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = ServletUtil.getCookie(request, Constant.COOKIE_TICKET_KEY);
        String ticket = null;
        if (cookie == null || StrUtil.isEmpty(ticket=cookie.getValue())) {
            return null;
        }
        UserEntity user = (UserEntity) redisService.get(Constant.TICKET_CACHE_KEY + ticket);
        if (user != null) {
            // 只要一直在访问，登录信息就一直延续
            redisService.set(Constant.TICKET_CACHE_KEY + ticket, user, Constant.MAX_AGE_IN_SECONDS);
            ServletUtil.addCookie(response, Constant.COOKIE_TICKET_KEY, ticket, Constant.MAX_AGE_IN_SECONDS);
        }
        return user;
    }

}
